<template>
  <el-container class="documentIpt_all">
    <el-header
      class="documentIpt_header"
      height="150px">
      <el-alert
        title="请您先选择知识点并生成题目后，再进行组卷！"
        type="warning"
        show-icon
      />
      <p>大模型出题组卷</p>
      <!-- <el-breadcrumb
        class="p_bottom"
        separator=">>">
        <el-breadcrumb-item :to="{ path: '/' }">HOME</el-breadcrumb-item>
        <el-breadcrumb-item>AUTOMATIC-QUESTION</el-breadcrumb-item>
      </el-breadcrumb> -->
      <div class="doc_btn_box">
        <el-button
          size="medium"
          type="primary"
          plain
          style="
            width: 150px;
            height: 36px;
            font-size: 14px;
            margin-bottom: 15px;
            color: #222;
          "
          @click="goTopage2"
          >返回</el-button
        >
      </div>
    </el-header>

    <el-main class="documentIpt_main">
      <el-table
        :style="tableWidthStyle"
        empty-text="没有数据"
        :data="chapters">
        <!--          <el-table-column prop="value" label="知识点" @click="show"></el-table-column>-->
        <el-table-column
          prop="title"
          label="章节">
          <template v-slot:default="{ row }">
            <div class="topic-container">
              <h3 class="knowledge-title" @click="showTopic(row)">{{ row.title }}</h3>
              <el-checkbox  v-model="row.allChecked"
                            @change="toggleAllCheckboxes(row)"
              >全选</el-checkbox>
              <ul v-if="row.expanded">
                <li
                  v-for="con in row.content"
                  :key="con.point"
                  class="knowledge-cont">
                  <!-- 添加勾选框 -->
                  <el-checkbox
                    v-model="con.isChecked"
                    @change="handleCheckboxChange(row, con)"></el-checkbox>
                  {{ con.point }}
                </li>
              </ul>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 文档内容抽屉 -->
      <div class="side-panel">
        <div
          class="title-container"
          style="position: sticky; top: 0">
          <h2 class="title">文件预览</h2>
          <!-- <el-button
            class="close-btn"
            @click="handleClose">
            <el-icon
              class="el-icon--close"
              style="position: absolute; top: 0; right: 10px"
              >×</el-icon
            >
          </el-button> -->
        </div>
        <div style="height:calc(100% - 361px); overflow-y: auto;padding:10px;box-sizing:border-box;">
          <div v-if="selectedContent.length">
            <p v-for="(item, index) in selectedContent" :key="index+'s'" style="line-height:28px;">
              {{ item.summary }}
            </p>
          </div>
          <div
            v-if="fileContent"
            class="file-content">
            <pre class="auto-wrap">{{ fileContent }}</pre>
          </div>
        </div>

        <div class="drawer-footer">
          <div class="select-container">
            <div class="question_container" v-for="(item, index) in questionsTypeOptions" :key="item.value">
              <el-row>
                  <el-col :span="12" class="flex">
                    <div class="zj_label">{{ item.label }}数目</div>
                    <div>
                      <el-button @click="handleDeOrIn('de', 'count', index)">-</el-button>
                      <span style="display:inline-block;min-width:50px;text-align:center;">{{ item.count }}</span>
                      <el-button @click="handleDeOrIn('in', 'count', index)">+</el-button>
                    </div>
                  </el-col>

                <el-col :span="12" class="flex">
                  <div class="zj_label">{{ item.label }}分数</div>
                  <div>
                    <el-button @click="handleDeOrIn('de', 'score', index)">-</el-button>
                    <span style="display:inline-block;min-width:50px;text-align:center;">{{ item.score }}</span>
                    <el-button @click="handleDeOrIn('in', 'score', index)">+</el-button>
                  </div>
                </el-col>
              </el-row>
            </div>
            <el-select
              v-model="generateMode"
              placeholder="请选择生成方式"
              style="
                display: inline-block;
                margin-top: 10px;
                box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.3);
                width: 250px;
              ">
              <el-option
                v-for="item in generateModeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-select
              v-model="difficultyLevel"
              collapse-tags
              style="
                display: inline-block;
                margin-top: 10px;
                box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.3);
                width: 250px;
              "
              placeholder="请选择生成题目的难度等级">
              <el-option
                v-for="item in difficultyLevelOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div class="buttons-container">
            <el-button
              size="medium"
              type="primary"
              class="documentIpt_btn"
              @click="generateQuestions"
              v-loading="btnLoading"
              >组卷</el-button
            >
             <el-button
              size="medium"
              type="warning"
              class="save_btn"
              @click="saveAndClose"
              >完成</el-button
            >
          </div>

          <!-- 提示信息 -->
          <el-alert
            v-if="showSuccessMessage"
            type="success"
            :closable="false"
            style="display: inline-block">
            传输成功
          </el-alert>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script lang="ts">
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import { Ref, computed, reactive, ref, watch } from "vue";
import { ElMessage, genFileId, UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import { Document, UploadFilled } from "@element-plus/icons-vue";
import PageResult from "@/views/PageResult.vue";
import { useCounter } from "@/utils/useCounter";
//知识点内容
interface Con {
  point: string;
  text: string;
  isChecked: boolean;
}
//章节
interface Chapter {
  content: Con[];
  title: string;
  allChecked: boolean; // 新增全选状态字段
}

interface uploadCon {
  summary: string;
  content: string;
}

// 定义 jsonData 的类型
type JsonData = Chapter[];
export default {
  name: "zujuan",
  components: { UploadFilled },
  setup() {

    const { useStore } = require("../store/index.js");
    const store = useStore();
    const router = useRouter();
    const route = useRoute();
    // 使用 ref 定义单个响应式变量
    const showSuccessMessage = ref(false);
    const btnLoading = ref(false)
    interface QueItem {
      value: string,
      label: string,
      count: number,
      score: number
    }
     const questionsTypeOptions:QueItem[] = reactive([
      { value: "choice", label: "单选题", count: 0, score: 0 },
      { value: "judge", label: "判断题", count: 0, score: 0},
      { value: "fill", label: "填空题", count: 0, score: 0 },
      { value: "answer", label: "简答题", count: 0, score: 0 }
    ]);

    const generateModeOptions = reactive([
      { value: "text", label: "根据教材内容生成" },
      { value: "open", label: "开放式生成" },
    ]);

    const difficultyLevelOptions = reactive([
      { value: "easy", label: "简单" },
      //{ value: "中等", label: "中等" },
      { value: "difficulty", label: "困难" },
    ]);

    // 使用 ref 定义单个响应式变量
    // 使用 ref 定义单个响应式变量
    const questionType = ref("");
    const difficultyLevel = ref("");
    const generateMode = ref("");

    const fileContent = ref();
    const jsonData = ref<JsonData>([]);
    const bool = ref(true); // 初始条件，可以根据需要修改

    const toggleAllCheckboxes = (row: Chapter) => {
      // 切换所有子项的选中状态
      row.content.forEach(con => {
        con.isChecked = row.allChecked;
      });
      // 更新 selectedContent
      updateSelectedContent(row);
    };


    const updateSelectedContent = (row: Chapter) => {
      // 移除当前章节原有的选中项
      selectedContent.value = selectedContent.value.filter(
          item => !row.content.some(c => c.point === item.summary)
      );
      // 添加新选中的项
      row.content
          .filter(con => con.isChecked)
          .forEach(con => {
            selectedContent.value.push({
              summary: con.point,
              content: con.text || '', // 确保 content 不为 undefined
            });
          });
    };
    // 计算表格宽度样式
    const tableWidthStyle = computed(() => ({
      width: "60%",
      "text-align": "center",
      borderRadius: "10px",
    }));
    const goToSearchPage = function () {
      router.push({
        name: "Home",
      });
    };
    const goTopage2 = function () {
      router.push({
        name: "page2",
      });
    };
    const handleDeOrIn = function (type:string, prop:string, index:number) {
      let item = questionsTypeOptions[index]
      if (type === 'de' && item[prop=='count'?'count':'score']>0) {
        --item[prop=='count'?'count':'score']
      }
      if (type === 'in') {
        ++item[prop=='count'?'count':'score']
      }
    }
    const generateQuestions = () => {
      if (selectedContent.value.length == 0) {
        ElMessage.error("请至少选择一个考点");
        return
      }
      if (!difficultyLevel.value) {
        ElMessage.error("请选择难度等级");
        return
      }
      if (!generateMode.value) {
        ElMessage.error("请选择生成方式");
        return
      }
      let data = {
        generateMode: generateMode.value,
        level: difficultyLevel.value,
        data: selectedContent.value,
        courseId: route.query.courseId || localStorage.getItem('courseId'),
        courseName: route.query.courseName || localStorage.getItem('courseName'),
        choiceCount: 0,
        choiceScore: 0,
        fillCount: 0,
        fillScore: 0,
        answerCount: 0,
        shortAnswerScore: 0,
        judgeCount: 0,
        judgeScore: 0
      }

      questionsTypeOptions.map(item => {
        switch(item.value) {
          case 'choice':
            data.choiceCount = item.count
            data.choiceScore =  item.score
            break;
          case 'judge':
            data.judgeCount = item.count
            data.judgeScore =  item.score
            break;
          case 'fill':
            data.fillCount = item.count
            data.fillScore =  item.score
            break;
          case 'answer':
            data.answerCount = item.count
            data.shortAnswerScore =  item.score
            break;
        }
      })
      btnLoading.value = true
      axios
        .post(`${store.apiBaseURI}/paper`, data,{timeout:600000})
        .then((response) => {
          btnLoading.value = false
          // 确保response.status是200，即请求成功
          if (response.status !== 200) {
            throw new Error("Network response was not ok");
          }
          console.log("response.data", response.data.content);
          // 清空selectedContent（可选）
          selectedContent.value = [];
          fileContent.value = response.data.content;
          ElMessage.success("组卷成功！");
          window.parent.postMessage({id: response.data.exam_id, title: response.data.exam_title}, '*')
        })
        .catch((error) => {
          console.error(error);
          btnLoading.value = false
          if (error.response.data.code == 300) {
            ElMessage.error(error.response.data.msg)
            return
          }
          ElMessage.error("组卷失败！");
        });
    };

    // 关闭抽屉
    const handleClose = () => {
      bool.value = true;
      // fileContent.value = '';
    };
    // console.log('让我看看',store.chap)
    watch([route], ([nRoute], [pRoute]) => {
      // 第一次不进入
      jsonData.value = JSON.parse(localStorage.getItem('chap') || '[]')
    })

    jsonData.value = JSON.parse(localStorage.getItem('chap') || '[]');
    jsonData.value = JSON.parse(localStorage.getItem('chap') || '[]').map((chapter: Chapter) => ({
      ...chapter,
      allChecked: false, // 默认未全选
    }));
    // 处理数据
    const chapters = computed(() => {
      if (jsonData.value && jsonData.value.length > 0) {
        return jsonData.value;
      }
      // 如果没有数据，可以返回一个空数组或其他默认值
      return [];
    });
    const showTopic = (row: { expanded: boolean }) => {
      row.expanded = !row.expanded;
    };

    const selectedContent: Ref<uploadCon[]> = ref([]);
    // 选中取消选中
    const handleCheckboxChange = (
      chapter: Chapter,
      con: Con & {
        isChecked: boolean;
      }
    ) => {
      bool.value = false;
      fileContent.value = "";
      if (con.isChecked) {
        // 如果知识点被选中，则添加到selectedContent数组中
        selectedContent.value.push({
          summary: con.point,
          content: con.text,
        });
      } else {
        // 如果知识点被取消选中，则从selectedContent数组中移除
        const index = selectedContent.value.findIndex((item) => item.summary === con.point);
        if (index !== -1) {
          selectedContent.value.splice(index, 1);
        }
      }
    };

    const saveAndClose = () => {
      window.parent.postMessage({closeIframe: true}, '*')
    }

    return {
      store,
      questionsTypeOptions,
      generateModeOptions,
      difficultyLevelOptions,
      questionType,
      difficultyLevel,
      generateMode,
      showSuccessMessage,
      goToSearchPage,
      generateQuestions,
      fileContent,
      handleClose,
      chapters,
      showTopic,
      tableWidthStyle,
      bool,
      handleCheckboxChange,
      selectedContent,
      goTopage2,
      btnLoading,
      saveAndClose,
      handleDeOrIn,
      toggleAllCheckboxes
    };
  },
};
</script>
<style lang="less" scoped>
::v-deep.el-row {
  width: 100%;
}
.documentIpt_all {
  height: 100vh;
  background-image: url(../assets/main_bg.jpg);
  background-size: cover;
}
.documentIpt_header {
  padding: 0;
  background-size: cover;
  position: relative;
  p {
    position: absolute;
    top: 40px;
    left: 30%;
    transform: translateX(-50%);
    color: #304156;
    font-weight: 700;
    font-size: 35px;
  }
  p.shifted {
    transform: translateX(-500px); /* 原页面内容左移 */
    transition: transform 0.3s; /* 平滑过渡效果 */
  }
  .p_bottom {
    position: absolute;
    top: 110px;
    left: 30%;
    transform: translateX(-50%);
    /deep/ .el-breadcrumb__item > span {
      color: #ffffff;
      font-size: 15px;
      font-weight: normal;
    }
  }
  .p_bottom.shifted {
    transform: translateX(-480px); /* 原页面内容左移 */
    transition: transform 0.3s; /* 平滑过渡效果 */
  }
  .long-arrow-left {
    font-size: 24px; /* 设置字体大小 */
    font-weight: bold; /* 设置字体加粗 */
    margin-left: 5px;
  }
  .documentIpt_btn {
    position: absolute;
    top: 100px; /* 相对于页面的右上角定位 */
    right: -5px; /* 相对于页面的右上角定位 */
    background-color: transparent; /* 清除背景色 */
    border: none; /* 清除边框 */
    color: #fff; /* 设置文字颜色 */
    text-align: center;
    cursor: pointer;
  }
}
.doc_btn_box {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 1%;
  ::v-deep .el-button:focus, .el-button:hover {
    color: #222;
    background-color: #f0f8ff !important;
  }
}
.documentIpt_main {
  width: 98%;
  margin: 0 auto;
  padding: 0;
  height: 495px;
  position: relative;

  .left {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    width: 750px;
    height: 220px;
    background-color: #b49c73;
    border-radius: 5px;

    .upload {
      position: absolute;
      top: 20px;
      left: 50%;
      transform: translateX(-50%);
      width: 700px;
      height: 180px;
      padding: 10px;
    }
    .buttons-container {
      display: flex;
      justify-content: center;
      gap: 200px; /* 添加按钮之间的间距 */
    }
    .documentIpt_btn {
      width: 100px;
      height: 50px;
      background-color: wheat;
      border-color: wheat;
      color: black;
      font-size: 20px;
      font-weight: 800;
    }
  }
  .side-panel {
    position: fixed;
    top: 5px;
    right: 0%;
    bottom: 0;
    width: 650px;
    background: #f9f9f9;
    z-index: 2;
    overflow-y: auto;
    transition: right 0.3s;
    border: 1px solid #eaeaea; /* 添加边框 */
    box-shadow: -5px 0 5px rgba(0, 0, 0, 0.2);
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
  }
  .title-container {
    padding: 0;
    background: #409eff; /* 标题背景色 */
    border-bottom: 1px solid #eaeaea;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    display: flex; /* 使容器变为flex布局 */
  }
  .title {
    font-size: 20px;
    font-weight: bold;
    margin: 0;
    color: white;
    padding: 10px;
  }

  .side-panel.active {
    right: 0; /* 显示侧边面板 */
  }

  .file-content {
    padding: 20px;
    word-wrap: break-word; /* 允许长单词换行 */
    white-space: pre-wrap; /* 保持换行和空格 */
    height: 300px; /* 设置一个最小高度，以便内容能够显示 */
  }
  .auto-wrap {
    /* 强制内容在边界内换行 */
    word-wrap: break-word;
    /* 防止内容溢出容器 */
    overflow-wrap: break-word;
    white-space: pre-wrap; /* 保留空格和换行符，同时允许内容在边界内换行 */
  }
  .close-btn {
    display: block;
    width: 81%;
    padding: 0;
    background-color: transparent; /* 清除背景色 */
    border: none; /* 清除边框 */
    color: #fff; /* 设置关闭按钮文字颜色 */
    text-align: center;
    cursor: pointer;
  }
  /* 移除点击时的背景颜色变化效果 */
  .close-btn:hover {
    background-color: transparent;
  }
  .close-btn .el-icon--close {
    position: absolute;
    top: 0;
    right: 10px;
    font-size: 40px; /* 调整图标大小 */
    cursor: pointer;
  }

  .left.shifted {
    transform: translateX(-650px); /* 原页面内容左移 */
    transition: transform 0.3s; /* 平滑过渡效果 */
  }
  .drawer-footer {
    width: 100%;
    min-height: 280px;
  }
  .select-container {
    display: flex;
    justify-content: center;
    //gap: 200px; /* 添加按钮之间的间距 */
    flex-direction: column;
    padding-left: 15px;
    box-sizing: border-box;
    .question_container {
      display: flex;
      justify-content: space-between;
      margin-top: 10px;
    }
  }
  .buttons-container {
    display: flex;
    justify-content: center;
  }
  .documentIpt_btn {
    margin-top: 20px;
    width: 200px;
    height: 38px;
    font-size: 15px;
  }
  .save_btn {
    width: 80px;
    height: 38px;
    font-size: 15px;
    margin-top: 20px;
    margin-left: 30px;
  }
  .flex {
    display: flex;
    align-items: center;
  }
  .zj_label {
    min-width: 100px;
    font-size: 16px;
    margin-right: 20px;
    text-align-last: justify;
  }
}
::v-deep .el-loading-spinner{
  width:100% !important;
  height:50px !important;
  /*这个是自己想设置的 gif 加载动图*/
  background-image:url('@/assets/loading2.gif') !important;
  background-repeat: no-repeat !important;
  background-size: 50px 50px !important;
  background-position:center;
  /*覆盖 element-ui  默认的 50%    因为此处设置了height:100%,所以不设置的话，会只显示一半，因为被top顶下去了*/
  position: relative; /* 设置相对定位 */
}
</style>
